//
//  TabbarController.m
//  ChatForHot
//
//  Created by FLY on 2018/10/9.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "TabbarController.h"
#import "TabbarMenuView.h"
#import "HomeViewController.h"
#import "ChatListViewController.h"
#import "PersonalViewController.h"
#import "GuestModel.h"
#import "SayHiViewController.h"
#import "ChatDemoHelper.h"

//两次提示的默认间隔
static const CGFloat DefaultPlaySoundInterval = 1.0;

#define ChatListIndex 1

@interface TabbarController ()<TabbarmenuDelegate>


@property (nonatomic,strong) TabbarMenuView *tabbarMenuView;

@property(nonatomic,strong) ChatListViewController *chatListVC;

@property(nonatomic, strong) HomeViewController *localVC;

@property(nonatomic, strong) PersonalViewController *personalVC;

@property (nonatomic, assign) CGFloat menuOffset;

@property (nonatomic,strong) NSMutableArray *autoArray;

@property (strong, nonatomic) NSDate *lastSoundDate;

@end

@implementation TabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addTabbars];
    
    [self HOTCHATgetSayHelloInfo];
    
    [self HOTCHATloginHuanXin];
    
    [ChatDemoHelper shareHelper];
    [ChatDemoHelper shareHelper].HOTCHATtabbarVC = self;
    [[ChatDemoHelper shareHelper] asyncGroupFromServer];
    [[ChatDemoHelper shareHelper] asyncConversationFromDB];
    [[ChatDemoHelper shareHelper] asyncPushOptions];
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
}
#pragma mark addTabbars
- (void)addTabbars{
    self.tabBar.hidden = YES;
    
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:self.localVC];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:self.chatListVC];
    UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:self.personalVC];
    
    self.viewControllers = @[nav1,nav2,nav3];
    [self.tabbarMenuView HOTCHATselectMenuAtIndex:1];
    
}
#pragma make Menu Delegate
- (void)HOTCHATClcikMenuIndex:(NSInteger)index{
    self.selectedIndex = index;
    if (index == ChatListIndex) {
        
        [self HOTCHATupdateChatList];
    }
}

- (void)HOTCHATshowMenuView{
    //showView
    self.menuOffset = 0;
    [self HOTCHATmoveAction];
}
- (void)HOTCHAThiddenMenuView{
    //hiddenView
    self.menuOffset = HOTCHATTabMenuHeight;
    [self HOTCHATmoveAction];
}
- (void)HOTCHATmoveAction{
    // tell constraints they need update
    [self.view setNeedsUpdateConstraints];
    
    // update constraints now so we can animate the change
    [self.view updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}
- (void)updateViewConstraints{
    
    [super updateViewConstraints];
    
    [self.tabbarMenuView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(self.menuOffset);
        make.height.mas_equalTo(HOTCHATTabMenuHeight);
    }];
}
- (void)HOTCHATgetSayHelloInfo{
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:HOTCHATAPPINFO.accountid forKey:@"accountid"];
    [dic setValue:@"6" forKey:@"limit"];
    [dic setValue:HOTCHATAPPINFO.sex.integerValue == 0 ? @"1" : @"0" forKey:@"sex"];
    
    [NetWorkTool HOTCHATRequestWithStringURL:SAYHELLO_URL progress:^(NSProgress * _Nonnull progress) {
        
    } RequestWay:@"GET" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        
        if ([resultDictionary[@"code"] integerValue] == 0) {
            NSArray *dataArr = resultDictionary[@"data"];
            NSMutableArray *arr = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in dataArr) {
                
                UserInfoModel *model = [[UserInfoModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [arr addObject:model];
                
            }
            if (arr.count > 0) {
                
                [self performSelectorOnMainThread:@selector(HOTCHATsayHelloWithatdaArr:) withObject:arr waitUntilDone:YES];
            }
        }
        
    } FailureBlock:^(NSError * _Nonnull error) {
        
    }];
}
- (void)HOTCHATsayHelloWithatdaArr:(NSArray *)dataArr{
    
    SayHiViewController *sayHelloVC = [[SayHiViewController alloc]init];
    sayHelloVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    sayHelloVC.dataArr = dataArr;
    [self presentViewController:sayHelloVC animated:NO completion:^{
        
    }];
}
#pragma login huanxin
- (void)HOTCHATloginHuanXin{
    
    [[EMClient sharedClient] loginWithUsername:HOTCHATAPPINFO.IMUser password:HOTCHATAPPINFO.IMPassword completion:^(NSString *aUsername, EMError *aError) {
        if (!aError) {
            //login successful
            NSInteger unreadCount = [self HOTCHATsetupUnreadMessageCount];
            NSLog(@"%ld",(long)unreadCount);
        }else {
            //                                                NSLog(@"登录失败__%d",aError.code);
            [self performSelector:@selector(HOTCHATloginHuanXin) withObject:nil afterDelay:5];
        }
    }];
}
// 统计未读消息数
-(NSInteger)HOTCHATsetupUnreadMessageCount{
    [self HOTCHATupdateChatList];
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    [self.tabbarMenuView HOTCHATsetMessageBadges:unreadCount];
    
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    UIApplication *app = [UIApplication sharedApplication];
    app.applicationIconBadgeNumber = unreadCount;
    
    return unreadCount;
}
//透传信息 做的处理
- (void)HOTCHATreceiveTheCmdMessages:(NSArray *)aCmdMessages{
    if (aCmdMessages.count > 0) {
        //save
        NSDictionary *dic = [GuestModel HOTCHATsaveGuestArray:aCmdMessages];
        NSLog(@"%@",dic);
        //refresh
        [self.chatListVC HOTCHATrefreshGuestListData];
        
        
//        for (EMMessage *message in aCmdMessages) {
//            NSDictionary *ext = message.ext;
//            if ([message.body isKindOfClass:[EMCmdMessageBody class]]) {
//                EMCmdMessageBody *body = (EMCmdMessageBody *)message.body;
//                if ([body.action isEqualToString:ONENIGHTGift_CMD]) {
//                    [[NSNotificationCenter defaultCenter] postNotificationName:ONENIGHTGift_CMD_MSG object:ext];
//                }
//            }
//        }
    }
}
- (void)HOTCHATplaySoundAndVibrationForTheUid:(NSString *)uid{
    
//    if ( uid && ![uid isEqualToString:self.HOTCHATchatingIMUid] && ![uid isEqualToString:self.callIMUid]) {
//        [self addMsgUser:uid];
//    }
    [self HOTCHATupdateChatList];
//    [self ONENIGHTshowMsgViewWithUnReadCount:1];
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastSoundDate];
    if (timeInterval < DefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastSoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastSoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}

- (void)HOTCHATupdateChatList{
    if (self.selectedIndex == ChatListIndex) {
        if (self.viewControllers.count > ChatListIndex) {
            UINavigationController *nv = [self.viewControllers objectAtIndex:ChatListIndex];
            if ([nv isKindOfClass:[UINavigationController class]]) {
                if (nv.viewControllers.count == 1) {
                    [self.chatListVC tableViewDidTriggerHeaderRefresh];
                }
            }
        }
    }
}
//lazzy
- (HomeViewController *)localVC{
    
    if (_localVC == nil) {
        
        _localVC = [[HomeViewController alloc]init];
    }
    return _localVC;
}
- (ChatListViewController *)chatListVC{
    
    if (_chatListVC == nil) {
        
        _chatListVC = [[ChatListViewController alloc]init];
    }
    return _chatListVC;
}
- (PersonalViewController *)personalVC{
    
    if (_personalVC == nil) {
        
        _personalVC = [[PersonalViewController alloc]init];
    }
    return _personalVC;
}
- (TabbarMenuView *)tabbarMenuView{
    
    if (_tabbarMenuView == nil) {
        
        _tabbarMenuView = [[TabbarMenuView alloc]init];
        _tabbarMenuView.delegate = self;
        [self.view insertSubview:_tabbarMenuView aboveSubview:self.tabBar];
        [_tabbarMenuView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(HOTCHATTabMenuHeight);
        }];
    }
    return _tabbarMenuView;
}
@end
